#create variable for slum-level density
slum_dens = A %>% #filter(Wave == "Jai-Pat 2015" ) %>% 
  group_by(factor(A.A7_Area.Neighborhood)) %>%
  summarise(N = n(),
            Mean_Age = mean(Num(C.C4_Age), na.rm=T),
            SocDens_Mean = mean(SocDens, na.rm=T),
            SocDens_SD = sd(SocDens, na.rm=T),
            SocDens2_Mean = mean(SocDens2, na.rm=T),
            SocDens2_SD = sd(SocDens2, na.rm=T),
            AltSocDens_Mean = mean(AltSocDens, na.rm=T),
            AltSocDens_SD = sd(AltSocDens, na.rm=T),
            City = City[which.max(tabulate(factor(City)))],
            Wave = Wave[which.max(tabulate(factor(Wave)))]) %>%
  mutate(SocDens_Hi = SocDens_Mean > median(SocDens_Mean),
         SocDens2_Hi = SocDens2_Mean > median(SocDens2_Mean),
         AltSocDens_Hi = AltSocDens_Mean > median(AltSocDens_Mean))

slum_dens = slum_dens  %>% arrange(City, Wave) %>% mutate(Neigh = seq(1:nrow(slum_dens)) ) %>% data.frame()

#mean(slum_dens$SocDens_Mean) #-0.08064637
#sd(slum_dens$SocDens_Mean) #0.3618956

A$NeighDens = slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'SocDens_Mean']
A$NeighDens2 = slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'SocDens2_Mean']
A$NeighDens_Hi = as.numeric(slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'SocDens_Hi'])
A$NeighDens2_Hi = as.numeric(slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'SocDens2_Hi'])
A$AltNeighDens = slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'AltSocDens_Mean']
A$AltNeighDens_Hi = as.numeric(slum_dens[match(A$A.A7_Area.Neighborhood, slum_dens$factor.A.A7_Area.Neighborhood.),'AltSocDens_Hi'])

rm(slum_dens)